package com.lq.JDBC;

import com.alibaba.druid.pool.DruidDataSource;
import org.junit.Test;

import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;
import java.util.Random;

public class TerstDruid {
    @Test
    public void testConn() throws SQLException {
        // 1、创建数据源
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
        dataSource.setUrl("jdbc:mysql://127.0.0.1:3306/jdbc_test?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=Asia/Shanghai&useServerPrepStmts=true&cachePrepStmts=true");
        dataSource.setUsername("root");
        dataSource.setPassword("root");

        Connection connection = dataSource.getConnection();
        System.out.println(connection);
    }

    @Test
    public void testConn2() throws SQLException, IOException {
        // 1、创建数据源
        DruidDataSource dataSource = new DruidDataSource();
        Properties properties = new Properties();
        properties.load(Thread.currentThread().getContextClassLoader().getResourceAsStream("druid.properties"));
        dataSource.configFromPropety(properties);

        Connection connection = dataSource.getConnection();
        connection.close();
        System.out.println(dataSource);
    }

    @Test
    public void testConn3() throws SQLException, IOException, InterruptedException {
        // 1、创建数据源
        DruidDataSource dataSource = new DruidDataSource();
        Properties properties = new Properties();
        properties.load(Thread.currentThread().getContextClassLoader().getResourceAsStream("druid.properties"));
        dataSource.configFromPropety(properties);

        //创建500个线程进行数据库的连接测试
        for (int i = 0; i < 500; i++) {
            new Thread(()->{
                try {
                    Connection connection = dataSource.getConnection();
                    // 执行一段时间
                    Thread.sleep(new Random().nextInt(1000));
                    connection.close();
                }catch (SQLException | InterruptedException e){
                    e.printStackTrace();
                }
            }).start();
        }

        //主线程等待一段时间等上面500个线程执行完之后，打印数据源日志，这里如果时间过短则会抢在线程之前进行打印并结束
        Thread.sleep(6000);
        System.out.println(dataSource);
    }

}
